<template>
  <div>
    <div class="flex-center">
      <app-address ref="mapSelectAppAddressRef" @output="regionChange"/>
      <div class="flex-center">
        <el-input v-model="searchAddr" size="small" placeholder="输入地址进行搜索" class="m-r-10 m-l-10"
                  clearable style="width: 300px;"/>
        <el-button icon="el-icon-search" type="primary" size="small" @click="search">查询</el-button>
      </div>
    </div>
    <div class="flex-center m-t-10">
      <div>
      </div>
      <div class="map-loading flex-center" v-show="mapLoading === true">
        <div></div>
        <div class="f-s-16"><i class="el-icon-loading"></i>加载地图中...</div>
        <div></div>
      </div>
      <div v-show="mapLoading === false" id="amap"></div>
      <div></div>
    </div>
    <div class="dividing-line m-t-20"></div>
    <div class="flex-center m-t-20">
      <div>
        <span class="m-r-10">经度</span><span class="m-r-10 f-w-600 c-blue">{{ curLocation[0] }}</span>
        <span class="m-r-10">维度</span><span class="f-w-600 c-blue m-r-10">{{ curLocation[1] }}</span>
        <span class="m-r-10">地址</span><span class="f-w-600 c-blue">{{ addressOutput }}</span>
      </div>
      <div class="flex-center" v-if="readonly===false">
        <el-button type="primary" size="small" @click="confirmLocation">确定</el-button>
        <el-button type="primary" size="small" plain @click="doCancel">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import {listNotEmpty, msgError, isNull, equals, isStringEmpty, isTrue, isListEmpty} from "@/util/common-util";
import AppAddress from "@/components/business/app-address";
import {mapConfig} from "@/components/business/map-config";

export default {
  name: "map-select-location-content",
  components: {AppAddress},
  props: {
    initLocation: {
      type: Array,
      default: () => []
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      mapLoading: false,
      map: {},
      locationMarker: {},
      curLocation: [],
      hasLocationFlag: false,
      searchAddr: '',
      provinceId: '340000',
      cityId: '340100',
      areaId: '340104',
      address: '',
      addressOutput: '',
      regionOutput: {}
    }
  },
  created() {
    if (listNotEmpty(this.initLocation) && !isStringEmpty(this.initLocation[0]) && !isStringEmpty(this.initLocation[1])) {
      this.curLocation = [Number(this.initLocation[0]), Number(this.initLocation[1])]
      this.hasLocationFlag = true
    } else {
      this.curLocation = [117.230799, 31.852396] // 合肥
    }
  },
  mounted() {
    // 初始化 省市区
    this.$refs.mapSelectAppAddressRef.init(this.provinceId, this.cityId, this.areaId)
    setTimeout(()=>{
      this.initMap();
    },2000)

  },
  beforeDestroy() {
    this.map && this.map.destroy();
  },
  methods: {
    hide() {
      this.$emit('hide')
    },
    doCancel() {
      this.hide()
    },
    initMap() {
      this.mapLoading = true
      AMapLoader.load({
        "key": mapConfig.key,
        // "version": "2.0",          // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        "plugins": ['AMap.Geocoder'],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        console.log("AMap")
        console.log(AMap)
        this.map = new AMap.Map('amap', {
          zoom: 12,
          center: this.curLocation,
          defaultCursor: 'crosshair'
        });
        this.map.on('click', this.setLnglat);
        this.locationMarker = this.initMapMarker()
        this.locationMarker.setMap(this.map);
        this.mapLoading = false

        if (isTrue(this.hasLocationFlag)) {
          this.setMarkderLocation(this.curLocation[0], this.curLocation[1])
          this.resetMapLocation()
          setTimeout(() => {
            this.hasLocationFlag = false
          }, 1000)
        }
      }).catch(e => {
        console.error(e);
        msgError("加载地图失败")
        this.mapLoading = false
      })
    },
    setLnglat(e) {
      this.setMarkderLocation(e.lnglat.getLng(), e.lnglat.getLat())
    },
    setMarkderLocation(lng, lat) {
      this.curLocation = [lng, lat]
      this.locationMarker.setPosition(this.curLocation)
      this.getAddressForOutput(lng, lat)
    },
    resetMapLocation() {
      this.map.setCenter(this.curLocation)
    },
    initMapMarker() {
      return new AMap.Marker({
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: this.curLocation,
        offset: new AMap.Pixel(-13, -30)
      })
    },
    confirmLocation() {
      this.$emit('change', this.curLocation, this.addressOutput, this.regionOutput)
      this.hide()
    },
    regionChange(_region) {
      if (isNull(_region)) return
      if (isNull(_region.province)) return
      this.provinceId = _region.province.key
      this.address = ''
      this.regionOutput = _region
      if (isNull(_region.city)) return
      this.cityId = _region.city.key
      this.address = _region.city.value
      if (isNull(_region.area)) return
      this.areaId = _region.area.key
      this.address = _region.city.value + _region.area.value
      if (isTrue(this.hasLocationFlag)) return
      this.doLocate(this.provinceId, this.address + this.searchAddr)
    },
    doLocate(_cityCode, _address) {
      const that = this
      new AMap.Geocoder({city: _cityCode}).getLocation(_address, function (status, result) {
        if (equals(status, 'complete') && listNotEmpty(result.geocodes)) {
          that.setMarkderLocation(result.geocodes[0].location.lng, result.geocodes[0].location.lat)
          that.resetMapLocation()
          return
        }
        msgError("定位无效")
      })
    },
    getAddressForOutput(lng, lat) {
      const that = this
      new AMap.Geocoder({city: this.provinceId}).getAddress([lng, lat], function (status, result) {
        if (equals(status, 'complete') && result.regeocode) {
          that.addressOutput = result.regeocode.formattedAddress;
        }
      })
    },
    search() {
      if (isStringEmpty(this.provinceId)) return msgError("请选择省...")
      this.doLocate(this.provinceId, this.address + this.searchAddr)
    }
  }
}
</script>

<style lang="scss" scoped>
#amap, .map-loading {
  height: 500px;
  width: 970px;
}

.el-input {
  ::v-deep .el-input__inner {
    height: 35px;
  }
}
</style>
